#include "WidgetManager.h"
#include "Widget.h"

namespace hgui
{
	template <> WidgetManager *Singleton<WidgetManager>::instance = nullptr;
	template <> const char *Singleton<WidgetManager>::className = "WidgetManager";

	WidgetManager::~WidgetManager()
	{
		for (UInt32 i = 0; i < mWidgets.size(); i++)
			mWidgets[i]->destroy();
		mWidgets.clear();
	}

	Widget *WidgetManager::findWidget(const std::string& widgetName)
	{
		for (UInt32 i = 0; i < mWidgets.size(); i++)
		{
			Widget *widget = mWidgets[i]->findWidget(widgetName);
			if (widget != nullptr)
				return widget;
		}
		return nullptr;
	}

	void WidgetManager::_destroyChildWidgets(Widget *parent)
	{
		WidgetArray childArray;
		for (UInt32 i = 0; i < mWidgets.size(); i++)
		{
			if (mWidgets[i]->isChild(parent))
			{
				childArray.push_back(mWidgets[i]);
				_destroyChildWidgets(mWidgets[i]);
			}
		}

		for (UInt32 i = 0; i < childArray.size(); i++)
			childArray[i]->destroy();
	}

	UInt32 WidgetManager::_widgetHasChild(Widget *parent)
	{
		UInt32 widgetsCount = 0;
		for (UInt32 i = 0; i < mWidgets.size(); i++)
		{
			if (mWidgets[i]->isChild(parent))
				widgetsCount++;
		}
		return widgetsCount;
	}

	void WidgetManager::destroyWidget(const std::string& widgetName)
	{
		Widget *widget = findWidget(widgetName);
		if (_widgetHasChild(widget) > 0)
			_destroyChildWidgets(widget);
		widget->destroy();
	}

	void WidgetManager::_deleteWidget(Widget *widget)
	{
		for (UInt32 i = 0; i < mWidgets.size(); i++)
		{
			if (widget == mWidgets[i])
			{
				delete mWidgets[i];
				mWidgets.erase(mWidgets.begin() + i);
			}
		}
	}

	void WidgetManager::printAllWidgets()
	{
		std::cout << "Widgets: " << std::endl;
		for (UInt32 i = 0; i < mWidgets.size(); i++)
			std::cout << "\t'" << mWidgets[i]->getWidgetName() << "'" << std::endl;
	}
} // namespace hgui